using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Web;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

namespace CustomNavigationDelegate.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("49c56c26-2871-4668-b680-463bbb86fc23")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        //public override void FeatureActivated(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            string url = "http://" + System.Environment.MachineName;            

            //Add provider entry to web.config
            SPWebConfigModification modifyWebConfig = new SPWebConfigModification();
            SPWebApplication webApp = SPWebApplication.Lookup(new Uri(url));

            modifyWebConfig.Path = "configuration/system.web/siteMap/providers";
            modifyWebConfig.Name = "add[@name=\"CustomNavigationProvider\"]";
            modifyWebConfig.Sequence = 0;
            modifyWebConfig.Owner = "add[@name=\"CustomNavigationProviderOwner\"]";
            modifyWebConfig.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modifyWebConfig.Value = "<add name=\"CustomNavigationProvider\" type=\"CustomNavigationDelegate.CustomNavigation, CustomNavigationDelegate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a42a891c9d3b2120\" NavigationType=\"Current\"/>";
            webApp.WebConfigModifications.Add(modifyWebConfig);
            webApp.Update();
            webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

            using (SPSite navListSite = new SPSite(url))
            {
                using (SPWeb navListWeb = navListSite.OpenWeb())
                {
                    SPList list = navListWeb.Lists.TryGetList("Navigation");
                    if (list == null)
                    {
                        //Create navigation list
                        SPListTemplate template = navListWeb.ListTemplates["Custom List"];
                        navListWeb.AllowUnsafeUpdates = true;
                        navListWeb.Lists.Add("Navigation", "Data for custom sitemap provider navigation", template);
                        SPList navList = navListWeb.Lists["Navigation"];
                        navList.Fields.Add("URL", SPFieldType.Text, true);
                        navList.Fields.Add("Order0", SPFieldType.Number, true);
                        navList.Fields.AddLookup("Parent", navList.ID, false);
                        SPFieldLookup parent = (SPFieldLookup)navList.Fields["Parent"];
                        parent.LookupField = navList.Fields["Title"].InternalName;
                        navList.Update();
                        navList.Fields["Order0"].Title = "Order";
                        navList.Fields["Order0"].Update();

                        //Add a Home item to the list
                        SPListItem item = navList.Items.Add();
                        item["Title"] = "Home";
                        item["URL"] = "/";
                        item["Order0"] = "1";
                        item.Update();

                        //Modify the default view
                        SPView view = navList.Views["All Items"];
                        SPViewFieldCollection viewFields = view.ViewFields;
                        viewFields.Add("URL");
                        viewFields.Add("Order0");
                        viewFields.Add("Parent");
                        string query = @"<GroupBy Collapse=""FALSE"" GroupLimit=""30""><FieldRef Name=""Parent"" /></GroupBy><OrderBy><FieldRef Name=""Order0"" /></OrderBy>";
                        view.Query = query;
                        view.Update();

                        navListWeb.AllowUnsafeUpdates = true;
                    }
                }
            }
        }


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {            
            string url = "http://" + System.Environment.MachineName;            
            SPWebApplication webApp = SPWebApplication.Lookup(new Uri(url));                                    
            int count = webApp.WebConfigModifications.Count;

            for (int i = count - 1; i >= 0; i--)
            {
                if (webApp.WebConfigModifications[i].Owner == "add[@name=\"CustomNavigationProviderOwner\"]")
                {
                    webApp.WebConfigModifications.Remove(webApp.WebConfigModifications[i]);
                    webApp.Update();
                    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                }
            }                        
        }
                
        // Uncomment the method below to handle the event raised when a feature is upgrading.
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
